package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.juhe.sdk.ApiClient;
import com.juhe.sdk.common.Result;
import com.juhe.sdk.reqeust.EnterpriseTaxQueryRequest;
import com.juhe.sdk.response.BankCardHVerifyResponse;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.domain.vo.Record;
import com.ruoyi.project.system.mapper.SmTaxMapper;
import com.ruoyi.project.system.mapper.SysQueryMapper;
import com.ruoyi.project.system.service.ISysQueryPayService;
import com.ruoyi.project.system.service.ISysQueryService;
import com.ruoyi.project.system.service.SmSMSService;
import com.ruoyi.project.system.service.TencentService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.constant.CacheConstants.taxes_Result;
import static com.ruoyi.common.utils.DateUtils.parseDateToStr;
import static com.ruoyi.project.utils.SmHandler.handleTaxes;

/**
 * 进件记录Controller
 */
@Slf4j
@RestController
@RequestMapping("/query")
public class SysQueryController extends BaseController {

    @Autowired
    private ISysQueryService sysQueryService;

    @Autowired
    private ISysQueryPayService iSysQueryPayService;

    @Autowired
    private TencentService tencentService;

    @Autowired
    private SmSMSService smSMSService;

    @Autowired
    private SysQueryMapper sysQueryMapper;

    @Autowired
    private SmTaxMapper smTaxMapper;

    @Autowired
    private RedisCache redisCache;

    ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");

    @GetMapping("/reset/{id}")
    public AjaxResult reset(@PathVariable("id") @NotNull Long id) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            int i = sysQueryService.updateSysQuery(new SysQuery(id, ""));
            return success(i);
        } else {
            return error();
        }
    }

    @GetMapping("/shield/{id}")
    public AjaxResult shield(@PathVariable("id") Long queryId) {
        if (queryId == null) {
            return error("没有单号！");
        }
        SysQuery sysQuery = sysQueryService.selectSysQueryById(queryId);
        if (sysQuery == null && StringUtils.isEmpty(sysQuery.getQueryInfo())) {
            return error("无数据！");
        }
        JSONObject info = JSON.parseObject(sysQuery.getQueryInfo());
        if (sysQuery.getProductId() == 2) {
            info.getJSONObject("dttz").getJSONObject("retdata").getJSONObject("Flag").replace("executionlimited", 0);
//            info.getJSONObject("dttz").getJSONObject("retdata").remove("ExecutionLimited");
        } else {
            info.getJSONObject("grss").getJSONObject("retdata").replace("resultCode", 0);
//            info.getJSONObject("grss").getJSONObject("retdata").remove("detail");
        }
        return toAjax(sysQueryService.updateSysQuery(new SysQuery(queryId, info.toJSONString())));
    }

    /**
     * 即时查询项目
     */
    @GetMapping("/data")
    public AjaxResult query(String name, String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return error("没有单号！");
        }
        SysQueryPay sysQueryPay = iSysQueryPayService.selectSysQueryPayByOrderNo(orderNo);
        if (sysQueryPay == null) {
            return warn("不存在支付订单");
        } else if (!"SUCCESS".equals(sysQueryPay.getPayState())) {
            return warn("订单未支付");
        } else if (!sysQueryPay.getBody().equals(name)) {
            return warn("与查询类型不符");
        }
        SysQuery sysQuery = sysQueryService.selectSysQueryById(sysQueryPay.getQueryId());
        if (sysQuery != null && StringUtils.isNotEmpty(sysQuery.getQueryInfo())) {
            sysQuery.setUpdateTime(DateUtils.getNowDate());
        } else {
            AjaxResult query;
            if (sysQuery.getProductId() == 1) {
                query = sysQueryService.bigDataQueryPro(sysQuery);
            } else if (sysQuery.getProductId() == 2) {
                query = sysQueryService.bigDataQuery(sysQuery);
            } else if (sysQuery.getProductId() == 4) {
                query = sysQueryService.marryQuery(sysQuery, orderNo);
            } else if (sysQuery.getProductId() == 5) {
                query = sysQueryService.judicialQuery(sysQuery);
            } else {
                return error("没有此产品编号！");
            }
            for (String key : query.keySet()) {
                JSONObject value = (JSONObject) query.get(key);
                if (value.get("retdata") instanceof String) {
                    if (!"000000".equals(value.getString("retcode"))) {
                        return error("数据出错！");
                    }
                    String retdata = value.getString("retdata");
                    if ('[' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseArray(retdata));
                    } else if ('{' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseObject(retdata));
                    }
                    query.replace(key, value);
                }
            }
            String queryInfo = JSON.toJSONString(query);
            sysQueryService.updateSysQuery(new SysQuery(sysQuery.getId(), queryInfo));
            sysQuery.setQueryInfo(queryInfo);
        }
        if (StringUtils.isNotEmpty(sysQuery.getName())) {
            sysQuery.setName("**" + sysQuery.getName().substring(1));
        }
        if (StringUtils.isNotEmpty(sysQuery.getCardNo())) {
            sysQuery.setCardNo("******" + sysQuery.getCardNo().substring(6));
        }
        if (StringUtils.isNotEmpty(sysQuery.getMobile())) {
            sysQuery.setMobile("*******" + sysQuery.getMobile().substring(7));
        }
        return success(sysQuery);
    }

    /**
     * 获取企业纳税查询授权URL
     */
    @Anonymous
    @GetMapping("/taxesAuthUrl")
    public AjaxResult taxesAuthUrl(SysQuery smQuery) {
        if (StringUtils.isEmpty(smQuery.getMobile())) {
            return warn("缺少参数");
        }
        try {
            JSONObject response = sysQueryService.companyQuery(smQuery);
            if (!"000000".equals(response.getString("retcode"))) {
                log.error("taxesAuthUrl调用出错：", response.getString("retmsg"));
                return error(response.getString("msg"));
            }
            String authUrl = response.getJSONObject("retdata").getString("authUrl");
            String taskId = response.getJSONObject("retdata").getString("taskId");
            smQuery.setProductId(3);
            smQuery.setQueryInfo(taskId);
            smQuery.setRemark(authUrl);
            sysQueryService.insertSysQuery(smQuery);
            smTaxMapper.insertSmTax(smQuery.getId().intValue());
            return success().put("authUrl", authUrl).put("queryId", smQuery.getId());
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 轮询企业纳税获取状态
     */
    @Anonymous
    @GetMapping("/taxesStatus/{id}")
    public AjaxResult taxesStatus(@PathVariable("id") @NotNull(message = "没有单号") Integer id) {
        Tax tax = smTaxMapper.selectSmTaxByQueryId(id);
        if (tax == null) {
            String taskId = smTaxMapper.selectTaskIdByQueryId(id);
            //2.准备参数
            EnterpriseTaxQueryRequest param = new EnterpriseTaxQueryRequest();
            param.setTaskId(taskId);
            try {
                Result<BankCardHVerifyResponse> response = apiClient.queryReportResult(param);
                if (response.getCode() != 200) {
                    log.error("taxesStatus调用出错：" + response.getMsg());
                    return AjaxResult.error(202, response.getMsg());  //202
                }
                int resultCode = response.getData().getResultCode();
                smTaxMapper.updateSmTaxStatus(new Tax(id, param.getRequestId(), "" + resultCode));
                if (resultCode != 3) {
                    return AjaxResult.error(202, "状态未完成");  //202
                } else {
                    // 短信通知结果
                    String tel = sysQueryMapper.selectSysQueryById(id.longValue()).getMobile();
                    smSMSService.sendTaxSuccessResult(tel, id);
                }
            } catch (Exception e) {
                log.error("调用出错: {}", e);
                return error(e.getMessage());  //501
            }
        }
        String orderNo = smTaxMapper.selectPayStatusByQueryId(id);
        if (StringUtils.isEmpty(orderNo)) {
            return AjaxResult.error(204, "获取成功，未支付");   //204
        }
        return success(orderNo);  // 200
    }

    /**
     * 获取企业纳税收集结果
     */
    @Anonymous
    @GetMapping("/taxesResult/{on}")
    public AjaxResult taxesResult(@PathVariable("on") @NotNull(message = "没有单号") String orderNo) {
        SysQueryPay smPay = smTaxMapper.selectPayStatusByOrderNo(orderNo);
        if (smPay == null) {
            return warn("未进行支付！");
        } else if ("NOTPAY".equals(smPay.getPayState())) {
            return warn("未支付！");
        } else if ("REFUND".equals(smPay.getPayState())) {
            return warn("已退款不可见！");
        } else if ("SUCCESS".equals(smPay.getPayState())) {
            int validDayNum = 15;
            LocalDateTime validTime = LocalDateTime.ofInstant(smPay.getPayTime().toInstant(), ZoneId.systemDefault()).plusDays(validDayNum);
            String endTime = validTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (LocalDateTime.now().isAfter(validTime)) {
                return warn("查询订单已过有效期").put("endTime", endTime);
            }
            Integer queryId = smPay.getQueryId().intValue();
            TaxInfo taxInfo = smTaxMapper.selectSmTaxInfoByQueryId(queryId);
            if (taxInfo == null) {
                String taskId = smTaxMapper.selectTaskIdByQueryId(queryId);
                EnterpriseTaxQueryRequest param = new EnterpriseTaxQueryRequest();
                param.setTaskId(taskId);

                try {
                    // MGZ TODO 2025/8/2: 获取企业纳税收集结果
                    Result<com.alibaba.fastjson.JSONObject> response = apiClient.queryTaxReport(param);
                    logger.warn(queryId + "——>" + response.getData());
                    if (response.getCode() != 200) {
                        log.error("taxesResult调用出错：", response.getMsg());
                        return warn(response.getMsg());
                    } else {
                        com.alibaba.fastjson.JSONObject data = response.getData();

//                    com.alibaba.fastjson.JSONObject data = JSON.parseObject(readLine().toString());
                        for (String k : data.keySet()) {
                            if (data.containsKey(k)) {
                                Object obj = data.get(k);
                                if (obj instanceof JSONArray) {
                                    data.replace(k, data.getJSONArray(k).toJSONString());
                                } else if (obj instanceof JSONObject) {
                                    data.replace(k, data.getJSONObject(k).toJSONString());
                                }
                            }
                        }
                        taxInfo = data.toJavaObject(TaxInfo.class);
                        taxInfo.setQueryId(queryId);
                        smTaxMapper.insertSmTaxInfo(taxInfo);
                        sysQueryMapper.updateSysQuery(new SysQuery(queryId.longValue(), taxInfo.getCompanyName(), ""));
                        iSysQueryPayService.updateSysQueryPay(new SysQueryPay().setOrderNo(orderNo).setKeyword(taxInfo.getCompanyName()));
                    }
                } catch (Exception e) {
                    log.error("调用出错: {}", e);
                    return error(e.getMessage());
                }
            }
            return success(handleTaxes(taxInfo));
        } else {
            return warn("状态异常");
        }
    }

    /**
     * 查询个人不动产
     */
    @Anonymous
    @GetMapping("/immData")
    public AjaxResult immData(String orderNo) {
        return sysQueryService.immovablePropert(sysQueryMapper.getQueryByOrderNo(orderNo));
    }

    @Anonymous
    @GetMapping("/concealKeyword/{orderNo}")
    public AjaxResult concealKey(@PathVariable("orderNo") String orderNo) {
        AjaxResult result = new AjaxResult();
        SysQuery sysQuery = sysQueryMapper.getQueryByOrderNo(orderNo);

        result.put("createTime", parseDateToStr("yyyy-MM-dd HH:mm:ss", sysQuery.getCreateTime()));
        result.put("userId", sysQuery.getUserId());

        if (StringUtils.isNotEmpty(sysQuery.getName())) {
            result.put("name", "**" + sysQuery.getName().substring(1));
        }
        if (StringUtils.isNotEmpty(sysQuery.getCardNo())) {
            result.put("cardNo", "******" + sysQuery.getCardNo().substring(6));
        }
        if (StringUtils.isNotEmpty(sysQuery.getMobile())) {
            result.put("mobile", "*******" + sysQuery.getMobile().substring(7));
        }
        if (StringUtils.isNotEmpty(sysQuery.getMoreKeyword())) {
            String moreKeyword = sysQuery.getMoreKeyword();
            result.put("moreKeyword", "****" + (moreKeyword.length() < 8 ? moreKeyword : moreKeyword.substring(8)));
        }
        return result;
    }

    /**
     * 修改进件记录
     */
    @Anonymous
    @GetMapping("/authFace/{orderNo}")
    public AjaxResult authFace(@PathVariable("orderNo") String orderNo) {
        SysQuery sysQuery = sysQueryMapper.getQueryByOrderNo(orderNo);
        try {
            AjaxResult result = tencentService.sendIdentityInfoUserInfo(orderNo, sysQuery);

            sysQuery.setRemark(result.get("orderNo").toString());
            sysQueryService.updateSysQuery(sysQuery);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.warn(e.getMessage());
        }
    }

    /**
     * 获取进件记录详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        SysQuery sq = sysQueryService.selectSysQueryById(id);
        if (StringUtils.isNotEmpty(sq.getName())) {
            sq.setName("**" + sq.getName().substring(1));
        }
        if (StringUtils.isNotEmpty(sq.getCardNo())) {
            sq.setCardNo("******" + sq.getCardNo().substring(6));
        }
        if (StringUtils.isNotEmpty(sq.getMobile())) {
            sq.setMobile("*******" + sq.getMobile().substring(7));
        }
        return success(sq);
    }

    @GetMapping(value = "/on/{id}")
    public AjaxResult getInfoOn(@PathVariable("id") Long id) {
        Long userId = SecurityUtils.getUserId();
        if (SecurityUtils.isAdmin(userId)) {
            return success(sysQueryService.selectSysQueryById(id));
        } else {
            return error();
        }
    }

    /**
     * 新增进件记录
     */
    @Anonymous
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysQuery sysQuery) {
        if (redisCache.getCacheObject("enableThrEle")) {
            ThrEleResult thrEleResult = sysQueryService.verificationTwoEle(sysQuery);
            if (!thrEleResult.isPass()) {
                return warn(thrEleResult.getMsg());
            }
        }
        sysQueryService.insertSysQuery(sysQuery);
        return success(sysQuery.getId());
    }


    /**
     * 查询进件记录列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(SysQuery sysQuery) {
        startPage();
        List<SysQuery> list = sysQueryService.selectSysQueryList(sysQuery);
        for (SysQuery sq : list) {
            if (StringUtils.isNotEmpty(sq.getName())) {
                sq.setName("**" + sq.getName().substring(1));
            }
            if (StringUtils.isNotEmpty(sq.getCardNo())) {
                sq.setCardNo("******" + sq.getCardNo().substring(6));
            }
            if (StringUtils.isNotEmpty(sq.getMobile())) {
                sq.setMobile("*******" + sq.getMobile().substring(7));
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询进件记录列表
     */
    @Anonymous
    @GetMapping("/recordList")
    public List<Record> recordList(String mobile, String sign) {
        // 拉取数据
        return sysQueryService.getRecords(mobile, sign);
    }

    /**
     * 查询进件记录列表通过手机号
     */
    @Anonymous
    @GetMapping("/recordListByMobile")
    public AjaxResult recordListByMobile(String mobile, String code) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        String captcha = redisCache.getCacheObject(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            return AjaxResult.error(4002, "验证码失效");
        }
        redisCache.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(code, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 拉取数据
        return AjaxResult.success(sysQueryService.getRecords(mobile, null));
    }

    /**
     * 修改进件记录
     */
    @PutMapping
    @Anonymous
    public AjaxResult edit(@RequestBody SysQuery sysQuery) {
        return toAjax(sysQueryService.updateSysQuery(sysQuery));
    }

}
